
package com.funo.commhelper.components.increment;

import com.funo.commhelper.R;
import com.funo.commhelper.interfaces.CallBackListener;
import com.funo.commhelper.util.CommonUtil;
import com.funo.commhelper.util.http.NetUtils;
import com.funo.increment.MyUtil;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 增量升级版本更新。 这个类只是用来查询当前服务器版本信息。
 * 
 * @author suchangjun
 */
public class IncrementUpdateVersion implements CallBackListener {

    private static final String httpUrl = null;// 查询版本信息的地址。

    private static final String TAG = "IncrementUpdateVersion";

    private Activity activity;
    
    private Context context;

    private VersionData data;

    private MyReceive myReceive = new MyReceive();

    /**
     * @param activity 如果这个是tab的之类，那么要是他的父亲，应为这个会用来你作为一个对话的父窗口。
     */
    public  IncrementUpdateVersion(Activity activity) {
        if(activity==null)
        {
            return;
        }
        this.activity = activity;// CommonUtil.getAppUpdateDialog  这个函数要用到activity。
        context=activity.getApplicationContext();
        beginCheckVersionThread();
    }

    /**
     * 销毁资源。
     */
    public void destory() {
        try {
            activity=null;
            context=null;
            data = null;
            context = null;
            myReceive = null;
            if (handler != null) {
                handler.removeMessages(beginDownNewVersion);
                handler.removeMessages(noNewVersion);
                handler = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unRegisterBrocase() {
        if (context != null) {
            if (myReceive != null) {
                context.unregisterReceiver(myReceive);
            }
        }
    }

    /**
     * 查询服务器版本，同事和本地版本判断，是否需要更新。
     */
    private void beginCheckVersionThread() {
        if (!CommonUtil.isNetworkAvailable(context)) {
            CommonUtil.showToastInfo(R.string.no_net, context);
            return;
        }
        // 由于http请求不能放到主线程里面，要不然会阻塞。
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String[] version = MyUtil.getLocalVersion(context);
                    if (version != null && version.length == 2) {

                        IncrementRequest request = getRequestObject(version[0], version[1]);
                        VersionData data = getServiceVersionInfo(request);

                        if (data != null) {
                            String newVersion = data.getLasterVersionCode();
                            String localVersion = request.getPrmIn().getVersionCode();
                            int newVersionInt = Integer.parseInt(newVersion);
                            int localVersionInt = Integer.parseInt(localVersion);
                            if (newVersionInt <= localVersionInt) {
                                // 当前版本已经是最新版本
                                handler.sendEmptyMessage(noNewVersion);
                            } else {
                                Message msg = new Message();
                                msg.what = beginDownNewVersion;
                                msg.obj = data;
                                handler.sendMessage(msg);

                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        });
        thread.start();
    }

    /**
     * 有新版本，这边坐处理。
     * 
     * @param data
     */
    private void dealWithHaveVersion(VersionData data) {
        if (data != null) {
            // 保持服务器版本信息，在回调函数会用到。
            this.data = data;
            // 弹出一个对话框，让用户选择是否要更新。
            CommonUtil.getAppUpdateDialog(activity, data.getDes(), this,
                    data.getLasterVersionCode());
        }

    }

    // * Intent intent = new Intent(MyContant.DOWN_PROCESS_ACTION);
    // * intent.putExtra(MyContant.DOWN_PROCESS, process);//百分比进度条
    // * intent.putExtra(MyContant.DOWN_PROCESS_TOTAL, all + "M");//这个是总大小
    // * intent.putExtra(MyContant.SUCCESS, isSuccess);//如果下载中间出错，这个就是false
    @Override
    public void callBack(int flag) {
        if (data != null) {
            context.registerReceiver(myReceive, new IntentFilter(
                    com.funo.increment.MyContant.DOWN_PROCESS_ACTION));
            com.funo.increment.MyUtil.startDownService(context, data.getDownUri(),
                    context.getPackageName(), data.getDownFileName());
        }

    }

    private final int noNewVersion = 1;

    private final int beginDownNewVersion = 2;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case noNewVersion: {
                    CommonUtil.showToastInfo(R.string.no_update, context);
                    break;
                }
                case beginDownNewVersion: {
                    try {
                        VersionData data = (VersionData) msg.obj;
                        dealWithHaveVersion(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    };

    class MyReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (com.funo.increment.MyContant.DOWN_PROCESS_ACTION.equals(intent.getAction())) {
                String process = intent.getStringExtra(com.funo.increment.MyContant.DOWN_PROCESS);// 下载进度条，单位是%
                String total = intent
                        .getStringExtra(com.funo.increment.MyContant.DOWN_PROCESS_TOTAL);// 总大小单位是M
                boolean isSuccess = intent.getBooleanExtra(com.funo.increment.MyContant.SUCCESS,
                        true);
                if ("0%".equals(process)) {
                    CommonUtil.showToastInfo(R.string.begin_down, context);
                } else if ("100%".equals(process)) {
                    CommonUtil.showToastInfo(R.string.end_down, context);
                    unRegisterBrocase();
                }

                if (!isSuccess) {
                    CommonUtil.showToastInfo(R.string.down_fail, context);
                    com.funo.increment.MyUtil.stopDownService(context);
                    unRegisterBrocase();
                }
            }

        }
    }

    /**
     * 获取服务器版本信息。
     */
    public static VersionData getServiceVersionInfo(IncrementRequest request) {
        try {

            if (request == null) {
                Log.e(TAG, "解析获取版本信息请求参数失败");
                return null;
            }

            String requestStr = com.alibaba.fastjson.JSON.toJSONString(request);

            // 测试数据
//
//             VersionData dataTest=new VersionData("v2.3beta",
//             "20","http://t.cn/zj63czF",
//             "http://t.cn/zj63czF", "通讯助手_v2.1.1.apk", "false", "测试包");
//            
//             IncrementRespondData prmOutTest=new IncrementRespondData("0",dataTest);
//             IncrementRespond respondTest=new IncrementRespond("1","38","0","",prmOutTest);
//             String vers=com.alibaba.fastjson.JSON.toJSONString(respondTest);

               String vers = NetUtils.doHttpPost(httpUrl, requestStr, false);

            if (vers != null) {
                IncrementRespond respond = com.alibaba.fastjson.JSON.parseObject(vers, IncrementRespond.class);
                // 请求成功
                if (respond.getRtncode().equals("0")) {
                    if (respond.getPrmOut() != null) {
                        VersionData data = respond.getPrmOut().getData();
                        return data;
                    }
                }
                Log.e(TAG, "返回数据：" + respond.toString());
                return null;
            }
            Log.e(TAG, "请求服务器信息失败");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "解析服务器信息失败");
        }
        return null;
    }

    /**
     * 获取请求的对象。
     * 
     * @return
     */
    public static IncrementRequest getRequestObject(String code, String name) {
        try {

            if (code != null && name != null) {
                VersionInfo versionInfo = new VersionInfo(code, name);
                IncrementRequest request = new IncrementRequest("1", "38", versionInfo);
                return request;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
